package com.steven.concurrency.example.jihetongbu;

import com.steven.concurrency.annoations.ThreadSafe;

import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * 声明一个线程安全的集合
 * 当线程一在执行移除操作的时候 线程二正好在获取当前索引，遂就引起了异常
 */
@ThreadSafe
public class VectorExam2 {

    /**
     * 方法一 （这里还可以使用stack）
     */
//    private static List<Integer> list = new Vector<>();
    /**
     * 方法二 (set map,集合都可以使用此方法)
     */
    private static List<Integer> list = Collections.synchronizedList(new ArrayList<>());
    //请求总数
    private static int clientTotal=5000;
    //并发数量
    private static int threadTotal=200;
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i <clientTotal ; i++) {
            final int cop=i;
            executorService.execute(()->{
                try {
                    semaphore.acquire();
                    add(cop);
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        System.out.println(list.size());
    }

    public static  void  add(int i){
        list.add(i);
    }
}
